package com.fxust.dialog;

/**
 * @auto johnking
 * @create 2017-12-17 下午9:18
 **/

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

import com.fxust.common.Constant;
import com.fxust.common.PropertiesHandler;
import com.fxust.dao.ThirdTableDao;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

/**
 *
 * 数据库配置对话框
 * @author fgq 2017年12月5日 下午4:03:40
 * @version V1.0
 */
public class DatabaseConfigDialog extends BaseDialog {

    private static Logger logger = Logger.getLogger(DatabaseConfigDialog.class);

    /**
     * 序列化ID
     */
    private static final long serialVersionUID = -1169507693085082265L;

    /**
     * 界面控件元素
     */
    private final JPanel dbConfigPanel = new JPanel();
    private JComboBox<String> dbComboBox = null;
    private JTextField ipTextField = null;
    private JTextField portTextField = null;
    private JTextField instanceTextField = null;
    private JTextField usernameTextField = null;
    private JPasswordField passwordTextField = null;
    private JButton testConnButton = null;
    private JButton saveInfoButton = null;

    /**
     *
     * 创建一个新的实例DatabaseConfigDialog.
     * @param frame
     * @param title
     */
    public DatabaseConfigDialog(Frame frame, String title) {
        super(frame, title);
        setBounds(100, 100, 295, 300);
        getContentPane().setLayout(new BorderLayout());

        dbConfigPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        dbConfigPanel.setBackground(Color.WHITE);
        dbConfigPanel.setLayout(null);
        getContentPane().add(dbConfigPanel, BorderLayout.CENTER);
        {
            JLabel dbTypeLabel = new JLabel("数据库类型:");
            dbTypeLabel.setHorizontalAlignment(SwingConstants.RIGHT);
            dbTypeLabel.setBounds(10, 30, 94, 15);
            dbConfigPanel.add(dbTypeLabel);

            dbComboBox = new JComboBox<String>();
            dbComboBox.setBounds(114, 27, 130, 21);
            dbConfigPanel.add(dbComboBox);

            JLabel ipLabel = new JLabel("数据库IP:");
            ipLabel.setHorizontalAlignment(SwingConstants.RIGHT);
            ipLabel.setBounds(10, 60, 94, 15);
            dbConfigPanel.add(ipLabel);

            ipTextField = new JTextField();
            ipTextField.setBounds(114, 57, 130, 21);
            ipTextField.setColumns(10);
            dbConfigPanel.add(ipTextField);

            JLabel portLabel = new JLabel("数据库端口:");
            portLabel.setHorizontalAlignment(SwingConstants.RIGHT);
            portLabel.setBounds(10, 90, 94, 15);
            dbConfigPanel.add(portLabel);

            portTextField = new JTextField();
            portTextField.setColumns(10);
            portTextField.setBounds(114, 87, 130, 21);
            dbConfigPanel.add(portTextField);

            JLabel instanceLabel = new JLabel("数据库实例:");
            instanceLabel.setHorizontalAlignment(SwingConstants.RIGHT);
            instanceLabel.setBounds(10, 120, 94, 15);
            dbConfigPanel.add(instanceLabel);

            instanceTextField = new JTextField();
            instanceTextField.setColumns(10);
            instanceTextField.setBounds(114, 117, 130, 21);
            dbConfigPanel.add(instanceTextField);

            JLabel usernameLabel = new JLabel("用户名:");
            usernameLabel.setHorizontalAlignment(SwingConstants.RIGHT);
            usernameLabel.setBounds(10, 150, 94, 15);
            dbConfigPanel.add(usernameLabel);

            usernameTextField = new JTextField();
            usernameTextField.setColumns(10);
            usernameTextField.setBounds(114, 147, 130, 21);
            dbConfigPanel.add(usernameTextField);

            JLabel passwordLabel = new JLabel("密码:");
            passwordLabel.setHorizontalAlignment(SwingConstants.RIGHT);
            passwordLabel.setBounds(10, 180, 94, 15);
            dbConfigPanel.add(passwordLabel);

            passwordTextField = new JPasswordField();
            passwordTextField.setColumns(10);
            passwordTextField.setBounds(114, 177, 130, 21);
            dbConfigPanel.add(passwordTextField);

            testConnButton = new JButton("连接测试");
            testConnButton.setBounds(34, 229, 100, 23);
            dbConfigPanel.add(testConnButton);

            saveInfoButton = new JButton("保存");
            saveInfoButton.setBounds(144, 229, 100, 23);
            dbConfigPanel.add(saveInfoButton);
        }
        addListener();
        initDatabaseInfo();
    }

    /**
     * 添加按钮监听器
     * @author fgq 2017年12月5日 下午4:01:06
     */
    private void addListener() {
        testConnButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                testDatabaseInfo();
            }
        });
        saveInfoButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                saveDatabaseInfo();
            }
        });
    }

    /**
     * 连接数据库测试
     * @author fgq 2017年12月5日 下午4:01:22
     */
    private void testDatabaseInfo(){
        boolean validResult = validDBInfo();
        if(validResult){
            JOptionPane.showMessageDialog(null, "连接测试成功", "提示信息", JOptionPane.INFORMATION_MESSAGE);
        }else{
            JOptionPane.showMessageDialog(null, "连接测试失败", "错误信息", JOptionPane.ERROR_MESSAGE);
            return;
        }
    }

    /**
     * 保存数据库信息
     * @author fgq 2017年12月5日 下午4:02:00
     */
    private void saveDatabaseInfo(){
        boolean validResult = validDBInfo();
        if(!validResult){
            JOptionPane.showMessageDialog(null, "连接测试失败", "错误信息", JOptionPane.ERROR_MESSAGE);
            return;
        }
        String dbType = (String)dbComboBox.getSelectedItem();
        String dbIp = ipTextField.getText();
        String dbPort = portTextField.getText();
        String instance = instanceTextField.getText();
        String username = usernameTextField.getText();
        String password = new String(passwordTextField.getPassword());
        String dbUrl = "";
        String driverName = "";
        if (Constant.DB_ORACLE.equals(dbType)) {
            driverName = Constant.ORACLE_DRIVER;
            dbUrl = "jdbc:oracle:thin:@" + dbIp + ":" + dbPort + "/" + instance;
        } else if (Constant.DB_MYSQL.equals(dbType)) {
            driverName = Constant.MYSQL_DRIVER;
            dbUrl = "jdbc:mysql://" + dbIp + ":" + dbPort + "/" + instance + "?useUnicode=true&characterEncoding=utf8";
        }
        PropertiesHandler.writePropertiesInfo("driverClassName", driverName);
        PropertiesHandler.writePropertiesInfo("url", dbUrl);
        PropertiesHandler.writePropertiesInfo("username", username);
        PropertiesHandler.writePropertiesInfo("password", password);
        JOptionPane.showMessageDialog(null, "保存数据库信息成功", "提示信息", JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * 从配置文件初始化数据库连接信息
     * @author fgq 2017年12月5日 下午4:02:58
     */
    private void initDatabaseInfo(){
        String userName = PropertiesHandler.readPropertiesConfigByKey("username");
        String password = PropertiesHandler.readPropertiesConfigByKey("password");
        String dbIp = "";
        String dbPort = "";
        String instance = "";
        String dbUrl = PropertiesHandler.readPropertiesConfigByKey("url");
        String[] dbInfo = dbUrl.split(":");
        if("oracle".equals(dbInfo[1])){
            dbIp = dbInfo[3].substring(1);
            dbPort = "1521";
            instance = dbInfo[4].substring(dbInfo[4].indexOf("/")+1);
            dbComboBox.addItem(dbInfo[1]);
        }else if("mysql".equals(dbInfo[1])){
            dbComboBox.addItem(dbInfo[1]);
            dbIp = dbInfo[2].substring(2);
            dbPort = "3306";
            instance = dbInfo[3].substring(dbInfo[3].indexOf("/")+1, dbInfo[3].indexOf("?"));
        }
        ipTextField.setText(dbIp);
        portTextField.setText(dbPort);
        instanceTextField.setText(instance);
        usernameTextField.setText(userName);
        passwordTextField.setText(password);
    }

    /**
     * 校验数据库信息
     * @author fgq 2017年12月5日 下午4:02:30
     * @return
     */
    private boolean validDBInfo(){
        String dbType = (String)dbComboBox.getSelectedItem();
        if (StringUtils.isBlank(dbType)) {
            JOptionPane.showMessageDialog(null, "数据库类型未选择，请确认", "错误信息", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        String dbIp = ipTextField.getText();
        if (StringUtils.isBlank(dbIp)) {
            JOptionPane.showMessageDialog(null, "数据库IP未输入，请确认", "错误信息", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        String dbPort = portTextField.getText();
        if (StringUtils.isBlank(dbPort)) {
            JOptionPane.showMessageDialog(null, "数据库端口未输入，请确认", "错误信息", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        String instance = instanceTextField.getText();
        if (StringUtils.isBlank(instance)) {
            JOptionPane.showMessageDialog(null, "数据库实例未输入，请确认", "错误信息", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        String username = usernameTextField.getText();
        if (StringUtils.isBlank(username)) {
            JOptionPane.showMessageDialog(null, "数据库用户名未输入，请确认", "错误信息", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        String password = new String(passwordTextField.getPassword());
        if (StringUtils.isBlank(password)) {
            JOptionPane.showMessageDialog(null, "数据库密码未输入，请确认", "错误信息", JOptionPane.ERROR_MESSAGE);
            return false;
        }
        String validSql = "";
        if (Constant.DB_ORACLE.equals(dbType)) {
            validSql = "SELECT 1 FROM DUAL";
        } else if (Constant.DB_MYSQL.equals(dbType)) {
            validSql = "SELECT 1";
        }
        boolean validResult = ThirdTableDao.validConnection(validSql);
        if(!validResult){
            return false;
        }
        logger.info("数据库测试连接成功");
        return true;
    }
}
